{{define "admin/role.html"}}
<!DOCTYPE html>
<html>

<head>
  {{template "layout/head.html" .}}
  <style type="text/css">
      td span{cursor: pointer}
  </style>
</head>

<body>
    <div class="wrapper">
        <div class="content-wrapper">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-md-12">
                        <div class="box">
                            <div class="box-header">
                                <div class="row " style="margin-left: 0px;padding-bottom: 5px;">
                                    <div class="col-md-6">
                                   
                                        <div class="form-horizontal searchPanel  form-inline  " >
                                            <label class=" control-label" style="padding-left:0px; ">应用:</label>
                                            <div class="btn-group" style="padding-left: 0px;">
                                                <select data-name="appid" class="form-control  feild-edit appidSelect" onchange="Role_operat.AppIdchange($(this).val())">
                                                    <option value="0" selected>不限</option>
                                                </select>
                                            </div>
                                        </div>
            
                                    </div>
                                    <div class="col-md-3">
            
                                    </div>
                                    <div class="col-md-3">
                                        <a class="btn btn-block btn-success" href="javascript:Role_operat.addOrModifyRole()">+ 添加角色</a>
                                    </div>
                                </div>
                                
                            </div><!-- /.box-header -->
                            <div class="box-body">
                                <div class="dataTables_wrapper form-inline dt-bootstrap">
                                    <div class="row">
                                        <div class="col-md-6"></div>
                                        <div class="col-md-6"></div>
                                    </div>
                                    <div class="row" style="width: 100%;">
                                        <div class="col-md-12 roleList">
                                            <table class="table table-bordered table-hover dataTable"> 
                                                <thead>
                                                    <tr>     
                                                        <td>角色ID</td> 
                                                        <td>角色名称</td> 
                                                        <td>所属应用</td> 
                                                        <td>状态</td>   
                                                        <td>角色描述</td>       
                                                        <td align="center">操作</td>   
                                                    </tr>  
                                                </thead>
                                                <tbody>

                                                </tbody>
                                                <tfoot style="display: none;">
                                                    <tr>
                                                        <td><span class="field" fieldName="pId"></span></td>
                                                        <td><span class="field" fieldName="pName"></span></td>
                                                        <td><span class="field" fieldName="pAppid"></span></td>
                                                        <td><span class="field spanBtn" fieldName="pState"></span></td>
                                                        <td><span class="field" fieldName="pDesc"></span></td>                                                       
                                                        <td align="center">
                                                            <span class="update btn btn-info btn-xs"    >修改</span>
                                                            <span class="rightManage btn btn-danger btn-xs"  >权限管理</span>                                                        
                                                        </td>
                                                     </tr>
                                                </tfoot>                                              
                                            </table>
                                            <div class="role_pagelist">       
                                                 <div class="pagination pull-right"></div>    
                                            </div>
                                        </div>
                                    </div>
            
                                </div>
                            </div><!-- /.box-body -->
                        </div><!-- /.box -->
                    </div>
                </div>
           
          
          
                <div class="addRoleDiv" style="display: none">
                    <form class="form-horizontal">
                        <div class="box-body">
                            <div class="form-inline row">
                                <label class="col-sm-3 control-label" >应用：</label>
                                <div class="col-sm-9">
                                    <select data-name="appid" class="form-control  feild-edit appidSelect">
                                    </select>
                                </div>
                            </div>
                            <div class="form-inline row">
                                <label class="col-sm-3 control-label" >角色名称：</label>
                                <div class="col-sm-9"><input type="text"  class="form-control  control-block add_roleName " /></div>
                            </div>
                            <div class="form-inline row">
                                <label class="col-sm-3 control-label" >描述：</label>
                                <div class="col-sm-9"><input type="text"  class="form-control  control-block  add_roledesc" /></div>
                            </div>
                        </div>
                    </form>
                </div>
               
          
          
                <div class="col-md-12" style="display: none;overflow-y: auto;" id="RoleRightPannel">
                    <div style="overflow-y: auto;">
                        <span style="margin-right:20px">颜色含义：</span>
                        <span style="color: red!important;margin-right:20px">分类</span>
                        <span style="color: blue!important;margin-right:20px">页面</span>
                        <span style="color:green!important;margin-right:20px">页面内功能</span>
                        <span style="margin-right:20px"><label><input type="checkbox" class="show_role_permission_btn">显示权限码</label></span>
                    </div>
                    <div style="clear: both;"></div>
                    <div class="ztree">
                    </div>
                </div>
          
            </div>
        </div>
    </div>

  {{template "layout/foot.html" .}}
  {{template "layout/iframePageFoot.html" .}}


    <link href="{{.pageContentPath}}/static/plugins/ztree_v3/css/metroStyle/metroStyle.css" rel="stylesheet"/>
    <script src="{{.pageContentPath}}/static/plugins/ztree_v3/js/jquery.ztree.all.js"></script>

    <link href="{{.pageContentPath}}/static/plugins/iCheck/all.css" rel="stylesheet"/>
    <script src="{{.pageContentPath}}/static/plugins/iCheck/icheck.min.js" type="text/javascript"></script>

    <link href="{{.pageContentPath}}/static/plugins/bootstrap-table/bootstrap-table.min.css/" rel="stylesheet"/>
    <script href="{{.pageContentPath}}/static/plugins/bootstrap-table/bootstrap-table.min.js/" ></script>
    <script src="{{.pageContentPath}}/static/plugins/jquery/jquery.pagination.min.js"></script>
<script type="text/javascript">
    /**
     * Created by Eric.Zhang on 2016/12/31.
     */
    var Role_operat = {
        appid:0,
        apps:{
            datas:[],
            getName : function (value) {
                var result = '';
                $(this.datas).each(function (i, vn) {
                    if (vn.pId == value) {
                        result = vn.pName;
                        return false;
                    }
                });
                return result;
            }
        },
    }

    Role_operat.pageInit=function(){   
        Role_operat.InitAppsData(function(){
            $(Role_operat.apps.datas).each(function (i,appID) {
                $(".appidSelect").append('<option value="'+appID.pId+'">'+appID.pName+'</option>');
            })    
            Role_operat.AppIdchange(Role_operat.appid);  
        })
        
    }
    Role_operat.InitAppsData = function (callback) {
            $.ajax({
                url:  page_content_path+'/api/system/authorize/app/getByPage',
                data:{pageIndex:1,pageSize:10000000,state:1},
                type: 'get',
                cache: true,
                success: function (result) {
                    if (!joyconn_layout.ValidataResult(result)) {
                        return;
                    }
                    if (result.data){
                        Role_operat.apps.datas=result.data;
                        if(Role_operat.apps.datas.length>0){
                            Role_operat.appid = Role_operat.apps.datas[0].pId
                        }
                    }
                    if(callback){
                        callback();
                    }
                }

            });
        }
      
    Role_operat.AppIdchange=function(appid){
        Role_operat.appid=appid;
        Role_operat.showList(1);
    }
    Role_operat.showList = function (pageIndex) {
        var pageSize=20;
        $('.roleList tbody').empty()
        $('.role_pagelist .pagination').empty()
        $.ajax({
            url: page_content_path+'/api/system/authorize/role/getpage',
            type:"get",
            data: { pageIndex: pageIndex, pageSize: pageSize, appid:Role_operat.appid },
            cache: false,
            success: function (data) {
                if (joyconn_layout.ValidataResult(data)) {
                    $( data.data).each(function(i,obj){
                        Role_operat.ShowItem(obj)
                    })
                    if(data.allcount>pageSize){
                        ShowPage($('.role_pagelist .pagination'), {
                            pno: pageIndex,
                            pagesize: pageSize,
                            allcount: data.allcount
                        }, function (pno) {
                            Role_operat.showList(pno);
                        });

                    }
                }

            }
        });
    }

    Role_operat.ShowItem = function (model) {
        var tr = $('.roleList tbody tr[data-id="'+model.pId+'"]')
        if(!tr||tr.length==0){
            tr = $($('.roleList tfoot').html()).attr("data-id",model.pId)
            $('.roleList tbody').append(tr)
        }
        $(tr).find('.field').each(function(i,span){
            var fieldName = $(span).attr("fieldName")
            if(fieldName=='pState'){
                $(span).html(model[fieldName]==0?"启用":"禁用")
            }else if(fieldName=='pAppid'){                
                $(span).html(Role_operat.apps.getName(model[fieldName]))
            }else{
                $(span).html(model[fieldName])
            }
        })
        $(tr).find('.spanBtn[fieldName="pState"]').unbind('click').click(function(){
            Role_operat.upataRoleState(model)
        })
        $(tr).find('.btn.update').unbind('click').click(function(){
            Role_operat.addOrModifyRole(model)
        })
        $(tr).find('.btn.rightManage').unbind('click').click(function(){
            Role_operat.rightManage(model)
        })
    }

    //添加角色
    Role_operat.addOrModifyRole = function (model) {
        var isAdd = !model;
        var title = (isAdd?'添加':'修改')
        var disElement = $($(".addRoleDiv").html());
        // $(Role_operat.apps.datas).each(function (i,app) {
        //     disElement.find('.appidSelect').append('<option '+(i==0?"selected":"")+' value="'+app.pId+'" title="'+app.pDesc+'">'+app.pName+'</option>')
        // })
        var dia = JoyDialog({
            titleText: title+'角色',
            width: '40em',
            content: disElement.get(0),
            buttonTextConfirm: title,
            buttonTextCancel: '取消',
            onClickConfirmBtn: function () {
                if(!model){
                    model={pState:1}
                }
                var postModel = JSON.parse(JSON.stringify(model))
                postModel.pName = $.trim($(disElement).find(".add_roleName").val());
                postModel.pDesc = $(disElement).find(".add_roledesc").val();
                postModel.pAppid = $(disElement).find(".appidSelect").val()*1;
                if (postModel.pName.length == 0) {
                    JoyDialog({
                        type:"toast_error",
                        infoText: '角色名称不能为空！',
                    });
                    return false;
                }
                JoyDialog.showLoading();
               
                $.ajax({
                    url: page_content_path+ '/api/system/authorize/role/'+(isAdd?"add":"update"),
                    data: JSON.stringify( postModel),
                    contentType:'application/json',
                    type: 'post',
                    success: function (data) {
                        JoyDialog.hideLoading();
                        if (!joyconn_layout.ValidataResult(data)) {
                            return;
                        }
                        if (data.code == 100001) {
                            dia.close();
                            Role_operat.ShowItem(postModel);
                            JoyDialog({
                                type:"toast_success",
                                infoText: title+'成功！',
                            });                            
                        } else {
                            JoyDialog({
                                type:"toast_error",
                                infoText: title+'成功！',
                            });
                        }
                    }
                });
                return false
            }
        });
        if(!isAdd){
            $(disElement).find(".add_roleName").val(model.pName);
            $(disElement).find(".add_roledesc").val(model.pDesc);
            $(disElement).find(".appidSelect").val(model.pAppid).attr('disabled','disabled');
        }
    }
    //禁用、启用角色
    Role_operat.upataRoleState = function (roleModel) {
        var pState = roleModel.pState==0?1:0;
        var text = roleModel.pState==1?"禁用":"启用";
        var dia = JoyDialog({
            titleText: '提示',
            content:'确认'+text+'角色吗？',
            buttonTextCancel:"取消",
            buttonTextConfirm:text,
            onClickConfirmBtn: ClickConfirmBtn
        });
        function ClickConfirmBtn(){
            JoyDialog.showLoading();
            $.ajax({
                url: page_content_path+ '/api/system/authorize/role/updateState',
                data: { Id: roleModel.pId,state:pState },
                type: 'post',
                success: function (data) {
                    JoyDialog.hideLoading();
                    if (!joyconn_layout.ValidataResult(data)) {
                        return;
                    }
                    if (data.code == 100001) {
                        JoyDialog({
                            type:"toast_success",
                            infoText: text+'成功！',
                        });
                        roleModel.pState=pState;
                        Role_operat.ShowItem(roleModel)
                    } else {
                        JoyDialog({
                            type:"toast_error",
                            infoText: text+'失败！',
                        });
                    }                   
                }
            });
           
        }
   
    }
    Role_operat.rightManage = function ( model) {
        var zTreeObj;
        var setting = {
            view: {
                showLine: true,
                showText: true,
                showIcon: false,
                selectedMulti: false,
                fontCss: function (treeId, treeNode) {
                    if (treeNode.pType == 1) {
                        return { color: "green" };
                    } else if (treeNode.pType == 2) {
                        return { color: "blue" };
                    } else if (treeNode.pType == 3) {

                        return { color: "red" };
                    }
                },
                addDiyDom:  function    (treeId, treeNode) {
                        var sObj = $("#" + treeNode.tId + "_span");
                        if (treeNode.editNameFlag || $("#diySpanStrNoteLable_" + treeNode.tId).length > 0) return;
                        var diySpanStr = "<span>";
                        diySpanStr += '<code class="role_Permission_code" style="display: none;">'+treeNode.pPermission+"</code>";
                        diySpanStr += "</span>";
                        sObj.after(diySpanStr);
                    }

            },
            callback: {
                onClick: function (event, treeId, treeNode) {
                    treeNode.checked = !treeNode.checked;
                    //zTreeObj.checkNode(treeNode, !treeNode.checked, false, false);
                }
            },
            check: {
                enable: true,
                chkStyle: "checkbox",
                chkboxType: { "Y": "", "N": "" }
            }
        }
        JoyDialog.showLoading();
        var tree_node ,role_resources,my_resources;
        var getdata1=$.ajax({
            url: page_content_path+ '/api/system/authorize/resource/getTree?appid='+model.pAppid,
            type: 'get',
            cache: false,
            success: function (data) {
                if (!joyconn_layout.ValidataResult(data)) {
                    return;
                }
                var txt = data.data;
                if (txt != '') {
                    tree_node = data.data;                   
                }
            }
        });
        var getdata2=$.get(page_content_path+"/api/system/authorize/role/getResourceIDsByRoleID?roleid="+model.pId,function (data) {
            if (!joyconn_layout.ValidataResult(data)) {
                return;
            }
            role_resources = data.data

        })
        var getdata3=$.get(page_content_path+"/api/system/authorize/user/permission/getMyRights?appid="+model.pAppid,function (data) {
            if (!joyconn_layout.ValidataResult(data)) {
                return;
            }
            my_resources = data.data

        })
        $.when(getdata1,getdata2,getdata3).then(function(){            
            JoyDialog.hideLoading();
            if( tree_node==undefined || role_resources==undefined||my_resources==undefined){
                return
            }
            // my_resources.splice($.inArray(15,my_resources),1);
            var container_div= $('<div style="overflow: auto;"></div>')
            container_div.append( $("#RoleRightPannel").html());
            container_div.height($(window).height()-200);
            var dia = JoyDialog({
                titleText: '权限设置',
                content: container_div.get(0),
                width: '40em',
                buttonTextConfirm: '提交',
                onClickConfirmBtn: onClickConfirmBtn
            });
            function onClickConfirmBtn() {
                var checkedNodes = zTreeObj.getCheckedNodes(true);
                var checkedArray = [];
                for (var i = 0; i < checkedNodes.length; i++) {
                    checkedArray .push(checkedNodes[i].pId);
                }
                $.ajax({
                    url: page_content_path+ '/api/system/authorize/role/updateRoleResource',
                    type: 'post',
                    data: {roleid:model.pId,resourceids:checkedArray},
                    success: function (data) {
                        if (!joyconn_layout.ValidataResult(data)) {
                            return;
                        }
                        if (data.code == 100001) {
                            JoyDialog({
                                type:"toast_success",
                                infoText: '修改成功！',
                            });
                        } else {
                            JoyDialog({
                                type:"toast_error",
                                infoText: '修改失败！',
                            });
                        }
                    }
                });

            }
            
            if (tree_node != null) {
                FillnodeName(role_resources,my_resources, tree_node.children);
                zTreeObj = $.fn.zTree.init(container_div.find("div.ztree"), setting, tree_node.children);
            }
            container_div.find(".show_role_permission_btn").iCheck({
                checkboxClass: 'icheckbox_square-blue',
                radioClass: 'iradio_square-blue',
                increaseArea: '20%' // optional
            }).on("ifChanged",function(event){
                container_div.find('.role_Permission_code').show();
            }).on("ifUnchecked",function(event){
                container_div.find('.role_Permission_code').hide();
            });
        })

    }
    //将后台输出的实体类添加name children title属性
    function FillnodeName(rightids,my_resources, nodes) {
        for (var i = 0; i < nodes.length; i++) {
            nodes[i].name = nodes[i].pName;
            // nodes[i].children = nodes[i].Children;
            nodes[i].title = nodes[i].pDesc;
            nodes[i].tId = nodes[i].pId;
            nodes[i].open = true;
            if ($.inArray(nodes[i].pId,my_resources )  <0) {
                nodes[i].chkDisabled = true
            }
            if ($.inArray(nodes[i].pId,rightids )  > -1) {
                nodes[i].checked = true
            }
            if (nodes[i].children && nodes[i].children.length > 0) {
                FillnodeName(rightids,my_resources,  nodes[i].children);
            }
        }
    }

    $(function () {
        Role_operat.pageInit();
    });
</script>
</body>

</html>
{{end}}